package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.pay.AlipayProperties;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping("pay")
public class PayController {
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private IOrderInfoService orderInfoService;

    @RequestMapping("payOrder")
    public void payOrder(String orderNo, HttpServletResponse response) throws AlipayApiException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //根据订单信息查询出订单信息
        OrderInfo orderInfo = orderInfoService.getOrderInfoByOrderNo(orderNo);
        if (orderInfo == null) {
            response.sendRedirect("http://localhost/50x.html");
        }

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturn_url());
        alipayRequest.setNotifyUrl(alipayProperties.getNotify_url());

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNo;
        //付款金额，必填
        String total_amount = orderInfo.getSeckillPrice()+"";
        //订单名称，必填
        String subject = orderInfo.getGoodName();
        //商品描述，可空
        String body = "this is product";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        PrintWriter writer = response.getWriter();
        //输出
        writer.println(result);
    }

    @RequestMapping("notify_url")
    public void notify_url(@RequestParam Map params, HttpServletResponse response) throws AlipayApiException, IOException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipay_public_key(),
                alipayProperties.getCharset(), alipayProperties.getSign_type()); //调用SDK验证签名
        PrintWriter writer = response.getWriter();
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = params.get("out_trade_no")+"";
            //更改订单状态
            orderInfoService.changPayStatus(out_trade_no, OrderInfo.STATUS_ACCOUNT_PAID);

            //输出
            writer.println("success");
        }else {//验证失败
            writer.println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    @RequestMapping("return_url")
    public void return_url(@RequestParam Map params, HttpServletResponse response) throws AlipayApiException, IOException {
        boolean signVerified = AlipaySignature.rsaCheckV2(params, alipayProperties.getAlipay_public_key(),
                alipayProperties.getCharset(), alipayProperties.getSign_type());
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = params.get("out_trade_no")+"";
            response.sendRedirect("http://localhost/order_detail.html?orderNo=" + out_trade_no);

        }else {//验证失败
            response.sendRedirect("http://localhost/50x.html");
        }
    }
}
